
<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>cleverhans.attacks.sparse_l1_descent &#8212; CleverHans  documentation</title>
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/alabaster.css" type="text/css" />
    <script id="documentation_options" data-url_root="../../../" src="../../../_static/documentation_options.js"></script>
    <script src="../../../_static/jquery.js"></script>
    <script src="../../../_static/underscore.js"></script>
    <script src="../../../_static/doctools.js"></script>
    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" />
   
  <link rel="stylesheet" href="../../../_static/custom.css" type="text/css" />
  
  
  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

  </head><body>
  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          

          <div class="body" role="main">
            
  <h1>Source code for cleverhans.attacks.sparse_l1_descent</h1><div class="highlight"><pre>
<span></span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">The SparseL1Descent attack.</span>
<span class="sd">&quot;&quot;&quot;</span>

<span class="kn">import</span> <span class="nn">warnings</span>
<span class="kn">from</span> <span class="nn">distutils.version</span> <span class="kn">import</span> <span class="n">LooseVersion</span>

<span class="kn">import</span> <span class="nn">tensorflow</span> <span class="k">as</span> <span class="nn">tf</span>

<span class="kn">from</span> <span class="nn">cleverhans.attacks.attack</span> <span class="kn">import</span> <span class="n">Attack</span>
<span class="kn">from</span> <span class="nn">cleverhans</span> <span class="kn">import</span> <span class="n">utils_tf</span>
<span class="kn">from</span> <span class="nn">cleverhans.utils_tf</span> <span class="kn">import</span> <span class="n">clip_eta</span><span class="p">,</span> <span class="n">random_lp_vector</span>
<span class="kn">from</span> <span class="nn">cleverhans.compat</span> <span class="kn">import</span> <span class="n">reduce_max</span><span class="p">,</span> <span class="n">reduce_sum</span><span class="p">,</span> \
  <span class="n">softmax_cross_entropy_with_logits</span>


<div class="viewcode-block" id="SparseL1Descent"><a class="viewcode-back" href="../../../source/attacks.html#cleverhans.attacks.SparseL1Descent">[docs]</a><span class="k">class</span> <span class="nc">SparseL1Descent</span><span class="p">(</span><span class="n">Attack</span><span class="p">):</span>
  <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">  This class implements a variant of Projected Gradient Descent for the l1-norm</span>
<span class="sd">  (Tramer and Boneh 2019). The l1-norm case is more tricky than the l-inf and l2</span>
<span class="sd">  cases covered by the ProjectedGradientDescent class, because the steepest</span>
<span class="sd">  descent direction for the l1-norm is too sparse (it updates a single</span>
<span class="sd">  coordinate in the adversarial perturbation in each step). This attack has an</span>
<span class="sd">  additional parameter that controls the sparsity of the update step. For</span>
<span class="sd">  moderately sparse update steps, the attack vastly outperforms Projected</span>
<span class="sd">  Steepest Descent and is competitive with other attacks targeted at the l1-norm</span>
<span class="sd">  such as the ElasticNetMethod attack (which is much more computationally</span>
<span class="sd">  expensive).</span>
<span class="sd">  Paper link (Tramer and Boneh 2019): https://arxiv.org/pdf/1904.13000.pdf</span>

<span class="sd">  :param model: cleverhans.model.Model</span>
<span class="sd">  :param sess: optional tf.Session</span>
<span class="sd">  :param dtypestr: dtype of the data</span>
<span class="sd">  :param kwargs: passed through to super constructor</span>
<span class="sd">  &quot;&quot;&quot;</span>

  <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">model</span><span class="p">,</span> <span class="n">sess</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">dtypestr</span><span class="o">=</span><span class="s1">&#39;float32&#39;</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Create a SparseL1Descent instance.</span>
<span class="sd">    Note: the model parameter should be an instance of the</span>
<span class="sd">    cleverhans.model.Model abstraction provided by CleverHans.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="nb">super</span><span class="p">(</span><span class="n">SparseL1Descent</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">sess</span><span class="o">=</span><span class="n">sess</span><span class="p">,</span>
                                          <span class="n">dtypestr</span><span class="o">=</span><span class="n">dtypestr</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">feedable_kwargs</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;eps&#39;</span><span class="p">,</span> <span class="s1">&#39;eps_iter&#39;</span><span class="p">,</span> <span class="s1">&#39;y&#39;</span><span class="p">,</span> <span class="s1">&#39;y_target&#39;</span><span class="p">,</span> <span class="s1">&#39;clip_min&#39;</span><span class="p">,</span>
                            <span class="s1">&#39;clip_max&#39;</span><span class="p">,</span> <span class="s1">&#39;grad_sparsity&#39;</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">structural_kwargs</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;nb_iter&#39;</span><span class="p">,</span> <span class="s1">&#39;rand_init&#39;</span><span class="p">,</span> <span class="s1">&#39;clip_grad&#39;</span><span class="p">,</span>
                              <span class="s1">&#39;sanity_checks&#39;</span><span class="p">]</span>

<div class="viewcode-block" id="SparseL1Descent.generate"><a class="viewcode-back" href="../../../source/attacks.html#cleverhans.attacks.SparseL1Descent.generate">[docs]</a>  <span class="k">def</span> <span class="nf">generate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Generate symbolic graph for adversarial examples and return.</span>

<span class="sd">    :param x: The model&#39;s symbolic inputs.</span>
<span class="sd">    :param kwargs: See `parse_params`</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="c1"># Parse and save attack-specific parameters</span>
    <span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">parse_params</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="n">asserts</span> <span class="o">=</span> <span class="p">[]</span>

    <span class="c1"># If a data range was specified, check that the input was in that range</span>
    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
      <span class="n">asserts</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">utils_tf</span><span class="o">.</span><span class="n">assert_greater_equal</span><span class="p">(</span><span class="n">x</span><span class="p">,</span>
                                                   <span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span><span class="p">,</span>
                                                           <span class="n">x</span><span class="o">.</span><span class="n">dtype</span><span class="p">)))</span>

    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
      <span class="n">asserts</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">utils_tf</span><span class="o">.</span><span class="n">assert_less_equal</span><span class="p">(</span><span class="n">x</span><span class="p">,</span>
                                                <span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span><span class="p">,</span>
                                                        <span class="n">x</span><span class="o">.</span><span class="n">dtype</span><span class="p">)))</span>

    <span class="c1"># Initialize loop variables</span>
    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">rand_init</span><span class="p">:</span>
      <span class="n">eta</span> <span class="o">=</span> <span class="n">random_lp_vector</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">shape</span><span class="p">(</span><span class="n">x</span><span class="p">),</span> <span class="nb">ord</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span>
                             <span class="n">eps</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">eps</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">dtype</span><span class="p">),</span> <span class="n">dtype</span><span class="o">=</span><span class="n">x</span><span class="o">.</span><span class="n">dtype</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
      <span class="n">eta</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">shape</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>

    <span class="c1"># Clip eta</span>
    <span class="n">eta</span> <span class="o">=</span> <span class="n">clip_eta</span><span class="p">(</span><span class="n">eta</span><span class="p">,</span> <span class="nb">ord</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">eps</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">eps</span><span class="p">)</span>
    <span class="n">adv_x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="n">eta</span>
    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">or</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
      <span class="n">adv_x</span> <span class="o">=</span> <span class="n">utils_tf</span><span class="o">.</span><span class="n">clip_by_value</span><span class="p">(</span><span class="n">adv_x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span><span class="p">)</span>

    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">y_target</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
      <span class="n">y</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">y_target</span>
      <span class="n">targeted</span> <span class="o">=</span> <span class="kc">True</span>
    <span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
      <span class="n">y</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span>
      <span class="n">targeted</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="k">else</span><span class="p">:</span>
      <span class="n">model_preds</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">get_probs</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
      <span class="n">preds_max</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_max</span><span class="p">(</span><span class="n">model_preds</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">keepdims</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
      <span class="n">y</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">to_float</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">equal</span><span class="p">(</span><span class="n">model_preds</span><span class="p">,</span> <span class="n">preds_max</span><span class="p">))</span>
      <span class="n">y</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">stop_gradient</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
      <span class="n">targeted</span> <span class="o">=</span> <span class="kc">False</span>
      <span class="k">del</span> <span class="n">model_preds</span>

    <span class="n">y_kwarg</span> <span class="o">=</span> <span class="s1">&#39;y_target&#39;</span> <span class="k">if</span> <span class="n">targeted</span> <span class="k">else</span> <span class="s1">&#39;y&#39;</span>

    <span class="k">def</span> <span class="nf">cond</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">_</span><span class="p">):</span>
      <span class="sd">&quot;&quot;&quot;Iterate until requested number of iterations is completed&quot;&quot;&quot;</span>
      <span class="k">return</span> <span class="n">tf</span><span class="o">.</span><span class="n">less</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">nb_iter</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">body</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">adv_x</span><span class="p">):</span>
      <span class="sd">&quot;&quot;&quot;Do a projected gradient step&quot;&quot;&quot;</span>

      <span class="n">labels</span><span class="p">,</span> <span class="n">_</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_or_guess_labels</span><span class="p">(</span><span class="n">adv_x</span><span class="p">,</span> <span class="p">{</span><span class="n">y_kwarg</span><span class="p">:</span> <span class="n">y</span><span class="p">})</span>
      <span class="n">logits</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">get_logits</span><span class="p">(</span><span class="n">adv_x</span><span class="p">)</span>

      <span class="n">adv_x</span> <span class="o">=</span> <span class="n">sparse_l1_descent</span><span class="p">(</span><span class="n">adv_x</span><span class="p">,</span>
                                <span class="n">logits</span><span class="p">,</span>
                                <span class="n">y</span><span class="o">=</span><span class="n">labels</span><span class="p">,</span>
                                <span class="n">eps</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">eps_iter</span><span class="p">,</span>
                                <span class="n">q</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">grad_sparsity</span><span class="p">,</span>
                                <span class="n">clip_min</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span><span class="p">,</span>
                                <span class="n">clip_max</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span><span class="p">,</span>
                                <span class="n">clip_grad</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">clip_grad</span><span class="p">,</span>
                                <span class="n">targeted</span><span class="o">=</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">y_target</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">),</span>
                                <span class="n">sanity_checks</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">sanity_checks</span><span class="p">)</span>

      <span class="c1"># Clipping perturbation eta to the l1-ball</span>
      <span class="n">eta</span> <span class="o">=</span> <span class="n">adv_x</span> <span class="o">-</span> <span class="n">x</span>
      <span class="n">eta</span> <span class="o">=</span> <span class="n">clip_eta</span><span class="p">(</span><span class="n">eta</span><span class="p">,</span> <span class="nb">ord</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">eps</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">eps</span><span class="p">)</span>
      <span class="n">adv_x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="n">eta</span>

      <span class="c1"># Redo the clipping.</span>
      <span class="c1"># Subtracting and re-adding eta can add some small numerical error.</span>
      <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">or</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">adv_x</span> <span class="o">=</span> <span class="n">utils_tf</span><span class="o">.</span><span class="n">clip_by_value</span><span class="p">(</span><span class="n">adv_x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span><span class="p">)</span>

      <span class="k">return</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="n">adv_x</span>

    <span class="n">_</span><span class="p">,</span> <span class="n">adv_x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">while_loop</span><span class="p">(</span><span class="n">cond</span><span class="p">,</span> <span class="n">body</span><span class="p">,</span> <span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">zeros</span><span class="p">([]),</span> <span class="n">adv_x</span><span class="p">),</span> <span class="n">back_prop</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
                             <span class="n">maximum_iterations</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">nb_iter</span><span class="p">)</span>

    <span class="c1"># Asserts run only on CPU.</span>
    <span class="c1"># When multi-GPU eval code tries to force all PGD ops onto GPU, this</span>
    <span class="c1"># can cause an error.</span>
    <span class="n">common_dtype</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">float32</span>
    <span class="n">asserts</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">utils_tf</span><span class="o">.</span><span class="n">assert_less_equal</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">eps_iter</span><span class="p">,</span>
                                                      <span class="n">dtype</span><span class="o">=</span><span class="n">common_dtype</span><span class="p">),</span>
                                              <span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">eps</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">common_dtype</span><span class="p">)))</span>

    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">sanity_checks</span><span class="p">:</span>
      <span class="k">with</span> <span class="n">tf</span><span class="o">.</span><span class="n">control_dependencies</span><span class="p">(</span><span class="n">asserts</span><span class="p">):</span>
        <span class="n">adv_x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">identity</span><span class="p">(</span><span class="n">adv_x</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">adv_x</span></div>

<div class="viewcode-block" id="SparseL1Descent.parse_params"><a class="viewcode-back" href="../../../source/attacks.html#cleverhans.attacks.SparseL1Descent.parse_params">[docs]</a>  <span class="k">def</span> <span class="nf">parse_params</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span>
                   <span class="n">eps</span><span class="o">=</span><span class="mf">10.0</span><span class="p">,</span>
                   <span class="n">eps_iter</span><span class="o">=</span><span class="mf">1.0</span><span class="p">,</span>
                   <span class="n">nb_iter</span><span class="o">=</span><span class="mi">20</span><span class="p">,</span>
                   <span class="n">y</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                   <span class="n">clip_min</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                   <span class="n">clip_max</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                   <span class="n">y_target</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                   <span class="n">rand_init</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
                   <span class="n">clip_grad</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
                   <span class="n">grad_sparsity</span><span class="o">=</span><span class="mi">99</span><span class="p">,</span>
                   <span class="n">sanity_checks</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
                   <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Take in a dictionary of parameters and applies attack-specific checks</span>
<span class="sd">    before saving them as attributes.</span>

<span class="sd">    Attack-specific parameters:</span>

<span class="sd">    :param eps: (optional float) maximum distortion of adversarial example</span>
<span class="sd">                compared to original input</span>
<span class="sd">    :param eps_iter: (optional float) step size for each attack iteration</span>
<span class="sd">    :param nb_iter: (optional int) Number of attack iterations.</span>
<span class="sd">    :param y: (optional) A tensor with the true labels.</span>
<span class="sd">    :param y_target: (optional) A tensor with the labels to target. Leave</span>
<span class="sd">                     y_target=None if y is also set. Labels should be</span>
<span class="sd">                     one-hot-encoded.</span>
<span class="sd">    :param clip_min: (optional float) Minimum input component value</span>
<span class="sd">    :param clip_max: (optional float) Maximum input component value</span>
<span class="sd">    :param clip_grad: (optional bool) Ignore gradient components</span>
<span class="sd">                      at positions where the input is already at the boundary</span>
<span class="sd">                      of the domain, and the update step will get clipped out.</span>
<span class="sd">    :param grad_sparsity (optional) Relative sparsity of the gradient update</span>
<span class="sd">                         step, in percent. Only gradient values larger</span>
<span class="sd">                         than this percentile are retained. This parameter can</span>
<span class="sd">                         be a scalar, or a vector of the same length as the</span>
<span class="sd">                         input batch dimension.</span>
<span class="sd">    :param sanity_checks: bool Insert tf asserts checking values</span>
<span class="sd">        (Some tests need to run with no sanity checks because the</span>
<span class="sd">         tests intentionally configure the attack strangely)</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="c1"># Save attack-specific parameters</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">eps</span> <span class="o">=</span> <span class="n">eps</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">rand_init</span> <span class="o">=</span> <span class="n">rand_init</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">eps_iter</span> <span class="o">=</span> <span class="n">eps_iter</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">nb_iter</span> <span class="o">=</span> <span class="n">nb_iter</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="n">y</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">y_target</span> <span class="o">=</span> <span class="n">y_target</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span> <span class="o">=</span> <span class="n">clip_min</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span> <span class="o">=</span> <span class="n">clip_max</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">clip_grad</span> <span class="o">=</span> <span class="n">clip_grad</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">grad_sparsity</span> <span class="o">=</span> <span class="n">grad_sparsity</span>

    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">eps</span><span class="p">,</span> <span class="nb">float</span><span class="p">)</span> <span class="ow">and</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">eps_iter</span><span class="p">,</span> <span class="nb">float</span><span class="p">):</span>
      <span class="c1"># If these are both known at compile time, we can check before anything</span>
      <span class="c1"># is run. If they are tf, we can&#39;t check them yet.</span>
      <span class="k">assert</span> <span class="n">eps_iter</span> <span class="o">&lt;=</span> <span class="n">eps</span><span class="p">,</span> <span class="p">(</span><span class="n">eps_iter</span><span class="p">,</span> <span class="n">eps</span><span class="p">)</span>

    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">y_target</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
      <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Must not set both y and y_target&quot;</span><span class="p">)</span>

    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_grad</span> <span class="ow">and</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">or</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">):</span>
      <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Must set clip_min and clip_max if clip_grad is set&quot;</span><span class="p">)</span>

    <span class="c1"># The grad_sparsity argument governs the sparsity of the gradient</span>
    <span class="c1"># update. It indicates the percentile value above which gradient entries</span>
    <span class="c1"># are retained. It can be specified as a scalar or as a 1-dimensional</span>
    <span class="c1"># vector of the same size as the input&#39;s batch dimension.</span>
    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">grad_sparsity</span><span class="p">,</span> <span class="nb">int</span><span class="p">)</span> <span class="ow">or</span> \
        <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">grad_sparsity</span><span class="p">,</span> <span class="nb">float</span><span class="p">):</span>
      <span class="k">if</span> <span class="ow">not</span> <span class="mi">0</span> <span class="o">&lt;</span> <span class="bp">self</span><span class="o">.</span><span class="n">grad_sparsity</span> <span class="o">&lt;</span> <span class="mi">100</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;grad_sparsity should be in (0, 100)&quot;</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
      <span class="bp">self</span><span class="o">.</span><span class="n">grad_sparsity</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">convert_to_tensor</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">grad_sparsity</span><span class="p">)</span>
      <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">grad_sparsity</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;grad_sparsity should either be a scalar or a vector&quot;</span><span class="p">)</span>


    <span class="bp">self</span><span class="o">.</span><span class="n">sanity_checks</span> <span class="o">=</span> <span class="n">sanity_checks</span>

    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">kwargs</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
      <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&quot;kwargs is unused and will be removed on or after &quot;</span>
                    <span class="s2">&quot;2019-04-26.&quot;</span><span class="p">)</span>

    <span class="k">return</span> <span class="kc">True</span></div></div>


<span class="k">def</span> <span class="nf">sparse_l1_descent</span><span class="p">(</span><span class="n">x</span><span class="p">,</span>
                      <span class="n">logits</span><span class="p">,</span>
                      <span class="n">y</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                      <span class="n">eps</span><span class="o">=</span><span class="mf">1.0</span><span class="p">,</span>
                      <span class="n">q</span><span class="o">=</span><span class="mi">99</span><span class="p">,</span>
                      <span class="n">clip_min</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                      <span class="n">clip_max</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                      <span class="n">clip_grad</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
                      <span class="n">targeted</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
                      <span class="n">sanity_checks</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
  <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">  TensorFlow implementation of the Dense L1 Descent Method.</span>
<span class="sd">  :param x: the input placeholder</span>
<span class="sd">  :param logits: output of model.get_logits</span>
<span class="sd">  :param y: (optional) A placeholder for the true labels. If targeted</span>
<span class="sd">            is true, then provide the target label. Otherwise, only provide</span>
<span class="sd">            this parameter if you&#39;d like to use true labels when crafting</span>
<span class="sd">            adversarial samples. Otherwise, model predictions are used as</span>
<span class="sd">            labels to avoid the &quot;label leaking&quot; effect (explained in this</span>
<span class="sd">            paper: https://arxiv.org/abs/1611.01236). Default is None.</span>
<span class="sd">            Labels should be one-hot-encoded.</span>
<span class="sd">  :param eps: the epsilon (input variation parameter)</span>
<span class="sd">  :param q: the percentile above which gradient values are retained. Either a</span>
<span class="sd">            scalar or a vector of same length as the input batch dimension.</span>
<span class="sd">  :param clip_min: Minimum float value for adversarial example components</span>
<span class="sd">  :param clip_max: Maximum float value for adversarial example components</span>
<span class="sd">  :param clip_grad: (optional bool) Ignore gradient components</span>
<span class="sd">                    at positions where the input is already at the boundary</span>
<span class="sd">                    of the domain, and the update step will get clipped out.</span>
<span class="sd">  :param targeted: Is the attack targeted or untargeted? Untargeted, the</span>
<span class="sd">                   default, will try to make the label incorrect. Targeted</span>
<span class="sd">                   will instead try to move in the direction of being more</span>
<span class="sd">                   like y.</span>
<span class="sd">  :return: a tensor for the adversarial example</span>
<span class="sd">  &quot;&quot;&quot;</span>

  <span class="n">asserts</span> <span class="o">=</span> <span class="p">[]</span>

  <span class="c1"># If a data range was specified, check that the input was in that range</span>
  <span class="k">if</span> <span class="n">clip_min</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
    <span class="n">asserts</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">utils_tf</span><span class="o">.</span><span class="n">assert_greater_equal</span><span class="p">(</span>
        <span class="n">x</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="n">clip_min</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">dtype</span><span class="p">)))</span>

  <span class="k">if</span> <span class="n">clip_max</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
    <span class="n">asserts</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">utils_tf</span><span class="o">.</span><span class="n">assert_less_equal</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="n">clip_max</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">dtype</span><span class="p">)))</span>

  <span class="c1"># Make sure the caller has not passed probs by accident</span>
  <span class="k">assert</span> <span class="n">logits</span><span class="o">.</span><span class="n">op</span><span class="o">.</span><span class="n">type</span> <span class="o">!=</span> <span class="s1">&#39;Softmax&#39;</span>

  <span class="k">if</span> <span class="n">y</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
    <span class="c1"># Using model predictions as ground truth to avoid label leaking</span>
    <span class="n">preds_max</span> <span class="o">=</span> <span class="n">reduce_max</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">keepdims</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
    <span class="n">y</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">to_float</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">equal</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="n">preds_max</span><span class="p">))</span>
    <span class="n">y</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">stop_gradient</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
  <span class="n">y</span> <span class="o">=</span> <span class="n">y</span> <span class="o">/</span> <span class="n">reduce_sum</span><span class="p">(</span><span class="n">y</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">keepdims</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>

  <span class="c1"># Compute loss</span>
  <span class="n">loss</span> <span class="o">=</span> <span class="n">softmax_cross_entropy_with_logits</span><span class="p">(</span><span class="n">labels</span><span class="o">=</span><span class="n">y</span><span class="p">,</span> <span class="n">logits</span><span class="o">=</span><span class="n">logits</span><span class="p">)</span>
  <span class="k">if</span> <span class="n">targeted</span><span class="p">:</span>
    <span class="n">loss</span> <span class="o">=</span> <span class="o">-</span><span class="n">loss</span>

  <span class="c1"># Define gradient of loss wrt input</span>
  <span class="n">grad</span><span class="p">,</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">gradients</span><span class="p">(</span><span class="n">loss</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>

  <span class="k">if</span> <span class="n">clip_grad</span><span class="p">:</span>
    <span class="n">grad</span> <span class="o">=</span> <span class="n">utils_tf</span><span class="o">.</span><span class="n">zero_out_clipped_grads</span><span class="p">(</span><span class="n">grad</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">clip_min</span><span class="p">,</span> <span class="n">clip_max</span><span class="p">)</span>

  <span class="n">red_ind</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">grad</span><span class="o">.</span><span class="n">get_shape</span><span class="p">())))</span>
  <span class="n">dim</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_prod</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">shape</span><span class="p">(</span><span class="n">x</span><span class="p">)[</span><span class="mi">1</span><span class="p">:])</span>

  <span class="n">abs_grad</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">abs</span><span class="p">(</span><span class="n">grad</span><span class="p">),</span> <span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="n">dim</span><span class="p">))</span>

  <span class="c1"># if q is a scalar, broadcast it to a vector of same length as the batch dim</span>
  <span class="n">q</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">broadcast_to</span><span class="p">(</span><span class="n">q</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">shape</span><span class="p">(</span><span class="n">x</span><span class="p">)[</span><span class="mi">0</span><span class="p">:</span><span class="mi">1</span><span class="p">]),</span> <span class="n">tf</span><span class="o">.</span><span class="n">float32</span><span class="p">)</span>
  <span class="n">k</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">floor</span><span class="p">(</span><span class="n">q</span> <span class="o">/</span> <span class="mi">100</span> <span class="o">*</span> <span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="n">dim</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">float32</span><span class="p">)),</span> <span class="n">tf</span><span class="o">.</span><span class="n">int32</span><span class="p">)</span>

  <span class="c1"># `tf.sort` is much faster than `tf.contrib.distributions.percentile`.</span>
  <span class="c1"># For TF &lt;= 1.12, use `tf.nn.top_k` as `tf.sort` is not implemented.</span>
  <span class="k">if</span> <span class="n">LooseVersion</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">__version__</span><span class="p">)</span> <span class="o">&lt;=</span> <span class="n">LooseVersion</span><span class="p">(</span><span class="s1">&#39;1.12.0&#39;</span><span class="p">):</span>
    <span class="c1"># `tf.sort` is only available in TF 1.13 onwards</span>
    <span class="n">sorted_grad</span> <span class="o">=</span> <span class="o">-</span><span class="n">tf</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">top_k</span><span class="p">(</span><span class="o">-</span><span class="n">abs_grad</span><span class="p">,</span> <span class="n">k</span><span class="o">=</span><span class="n">dim</span><span class="p">,</span> <span class="nb">sorted</span><span class="o">=</span><span class="kc">True</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
  <span class="k">else</span><span class="p">:</span>
    <span class="n">sorted_grad</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">abs_grad</span><span class="p">,</span> <span class="n">axis</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>

  <span class="n">idx</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">stack</span><span class="p">((</span><span class="n">tf</span><span class="o">.</span><span class="n">range</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">shape</span><span class="p">(</span><span class="n">abs_grad</span><span class="p">)[</span><span class="mi">0</span><span class="p">]),</span> <span class="n">k</span><span class="p">),</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
  <span class="n">percentiles</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">gather_nd</span><span class="p">(</span><span class="n">sorted_grad</span><span class="p">,</span> <span class="n">idx</span><span class="p">)</span>
  <span class="n">tied_for_max</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">greater_equal</span><span class="p">(</span><span class="n">abs_grad</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">expand_dims</span><span class="p">(</span><span class="n">percentiles</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">))</span>
  <span class="n">tied_for_max</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="n">tied_for_max</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">dtype</span><span class="p">),</span> <span class="n">tf</span><span class="o">.</span><span class="n">shape</span><span class="p">(</span><span class="n">grad</span><span class="p">))</span>
  <span class="n">num_ties</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_sum</span><span class="p">(</span><span class="n">tied_for_max</span><span class="p">,</span> <span class="n">red_ind</span><span class="p">,</span> <span class="n">keepdims</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>

  <span class="n">optimal_perturbation</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">sign</span><span class="p">(</span><span class="n">grad</span><span class="p">)</span> <span class="o">*</span> <span class="n">tied_for_max</span> <span class="o">/</span> <span class="n">num_ties</span>

  <span class="c1"># Add perturbation to original example to obtain adversarial example</span>
  <span class="n">adv_x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="n">utils_tf</span><span class="o">.</span><span class="n">mul</span><span class="p">(</span><span class="n">eps</span><span class="p">,</span> <span class="n">optimal_perturbation</span><span class="p">)</span>

  <span class="c1"># If clipping is needed, reset all values outside of [clip_min, clip_max]</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">clip_min</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">)</span> <span class="ow">or</span> <span class="p">(</span><span class="n">clip_max</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">):</span>
    <span class="c1"># We don&#39;t currently support one-sided clipping</span>
    <span class="k">assert</span> <span class="n">clip_min</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">clip_max</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span>
    <span class="n">adv_x</span> <span class="o">=</span> <span class="n">utils_tf</span><span class="o">.</span><span class="n">clip_by_value</span><span class="p">(</span><span class="n">adv_x</span><span class="p">,</span> <span class="n">clip_min</span><span class="p">,</span> <span class="n">clip_max</span><span class="p">)</span>

  <span class="k">if</span> <span class="n">sanity_checks</span><span class="p">:</span>
    <span class="k">with</span> <span class="n">tf</span><span class="o">.</span><span class="n">control_dependencies</span><span class="p">(</span><span class="n">asserts</span><span class="p">):</span>
      <span class="n">adv_x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">identity</span><span class="p">(</span><span class="n">adv_x</span><span class="p">)</span>

  <span class="k">return</span> <span class="n">adv_x</span>
</pre></div>

          </div>
          
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<h1 class="logo"><a href="../../../index.html">CleverHans</a></h1>








<h3>Navigation</h3>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../source/attacks.html"><cite>attacks</cite> module</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../source/model.html"><cite>model</cite> module</a></li>
</ul>

<div class="relations">
<h3>Related Topics</h3>
<ul>
  <li><a href="../../../index.html">Documentation overview</a><ul>
  <li><a href="../../index.html">Module code</a><ul>
  </ul></li>
  </ul></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
  <h3 id="searchlabel">Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>
    </div>
</div>
<script>$('#searchbox').show(0);</script>








        </div>
      </div>
      <div class="clearer"></div>
    </div>


  </body>
</html>